<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的网盘 - 用户登录</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-image: url('/static/images/test.png'); /* 替换为你的背景图片路径 */
            background-size: cover;
            background-position: center;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            padding: 0;
        }
        .container {
            background-color: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 400px;
            max-width: 100%;
        }
        .logo {
            text-align: center;
            margin-bottom: 20px;
        }
        .logo img {
            width: 100px;
        }
        h2 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        input[type="text"],
        input[type="email"],
        input[type="password"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #4a76e8;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #3c63d1;
        }
        .toggle-form {
            text-align: center;
            margin-top: 15px;
        }
        .toggle-form a {
            color: #4a76e8;
            text-decoration: none;
            font-size: 14px;
        }
        .toggle-form a:hover {
            text-decoration: underline;
        }
        .error-message {
            color: red;
            text-align: center;
            margin-top: 10px;
            font-size: 14px;
        }
    </style>
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
    <div class="container" id="form-container">
        <div class="logo">
            <img src="/static/images/logo.png" alt="我的网盘">
        </div>
        <div id="login-form-container">
            <h2>用户登录</h2>
            <form id="login-form" action="/user/signin" method="POST" onsubmit="return handleFormSubmit(event, this)">
                <label for="username">用户名</label>
                <input type="text" id="login-username" name="username" required>

                <label for="password">密码</label>
                <input type="password" id="login-password" name="password" required>

                <button type="submit">登录</button>
                <div class="error-message" id="login-error-message"></div>
            </form>
            <div class="toggle-form">
                <a href="#" onclick="toggleForm()">没有账号？去注册</a>
            </div>
        </div>
        <div id="register-form-container" style="display: none;">
            <h2>用户注册</h2>
            <form id="register-form" action="/user/signup" method="POST" onsubmit="return handleFormSubmit(event, this)">
                <label for="register-username">用户名</label>
                <input type="text" id="register-username" name="username" required>

                <label for="register-email">邮箱</label>
                <input type="email" id="register-email" name="email" required>

                <label for="register-password">密码</label>
                <input type="password" id="register-password" name="password" required>

                <label for="confirm-password">确认密码</label>
                <input type="password" id="confirm-password" name="confirm_password" required>

                <button type="submit">注册</button>
                <div class="error-message" id="register-error-message"></div>
            </form>
            <div class="toggle-form">
                <a href="#" onclick="toggleForm()">已有账号？去登录</a>
            </div>
        </div>
    </div>

    <script>
        let currentForm = 'login';

        function toggleForm() {
            if (currentForm === 'login') {
                document.getElementById('login-form-container').style.display = 'none';
                document.getElementById('register-form-container').style.display = 'block';
                currentForm = 'register';
            } else {
                document.getElementById('login-form-container').style.display = 'block';
                document.getElementById('register-form-container').style.display = 'none';
                currentForm = 'login';
            }
        }

        function validateLoginForm(form) {
            const username = form.querySelector('#login-username').value;
            const password = form.querySelector('#login-password').value;

            if (username.length < 3 || password.length < 5) {
                form.querySelector('.error-message').innerText = '用户名至少需要3个字符，密码至少需要5个字符';
                return false;
            }

            form.querySelector('.error-message').innerText = '';
            return true;
        }

        function validateRegisterForm(form) {
            const username = form.querySelector('#register-username').value;
            const email = form.querySelector('#register-email').value;
            const password = form.querySelector('#register-password').value;
            const confirmPassword = form.querySelector('#confirm-password').value;

            if (username.length < 3) {
                form.querySelector('.error-message').innerText = '用户名至少需要3个字符';
                return false;
            }

            if (password.length < 5) {
                form.querySelector('.error-message').innerText = '密码至少需要5个字符';
                return false;
            }

            if (password !== confirmPassword) {
                form.querySelector('.error-message').innerText = '两次输入的密码不一致';
                return false;
            }

            form.querySelector('.error-message').innerText = '';
            return true;
        }

        function handleFormSubmit(event, form) {
            console.log('Form submit event captured');
            event.preventDefault();

            if (currentForm === 'login' && !validateLoginForm(form)) {
                return;
            }

            if (currentForm === 'register' && !validateRegisterForm(form)) {
                return;
            }

            const formData = new FormData(form);
            const url = form.action;
            const urlEncodedData = new URLSearchParams(formData).toString();
            // 将 FormData 转换为 JSON 对象
            // const jsonFormData = {};
            // formData.forEach((value, key) => {
            //     jsonFormData[key] = value;
            // });

            $.ajax({
                url: url,
                method: form.method,
                data: formData,
                processData: false,  // 禁止 jQuery 对数据的处理
                contentType: false,
                //contentType: 'application/json',
                success: function(response) {
                    try {
                        const resp = JSON.parse(response);
                        console.log('Parsed Response:', resp); // 打印解析后的响应对象
                        if (resp.code === 200) {
                            if (resp.data && resp.data.Location) {
                                // 登录成功，重定向到指定位置
                                console.log('Redirecting to:', resp.data.Location); // 打印重定向的目标

                                // 将 username 和 token 存储到 localStorage
                                localStorage.setItem('username', resp.data.Username);
                                localStorage.setItem('token', resp.data.Token);

                                window.location.href = resp.data.Location;
                            } else {
                                // 注册成功，显示注册成功的提示
                                form.querySelector('.error-message').innerText = '注册成功，请点击登录进行登录';
                            }

                            //console.log('Redirecting to:', resp.data.Location); // 打印重定向的目标

                            // // 将 username 和 token 存储到 localStorage
                            // localStorage.setItem('username', resp.data.Username);
                            // localStorage.setItem('token', resp.data.Token);
                            
                            // window.location.href = resp.data.Location;
                        } else {
                            form.querySelector('.error-message').innerText = resp.msg;
                        }
                    } catch (error) {
                        console.error('Error parsing response:', error); // 打印解析错误
                        form.querySelector('.error-message').innerText = '账户名或密码错误';
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error); // 打印 AJAX 错误
                    form.querySelector('.error-message').innerText = '请求失败，请稍后再试';
                }
            });
        }
    </script>
</body>
</html>